package com.bearingnavi.android.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import android.text.format.DateFormat;

import de.mindpipe.android.logging.log4j.LogConfigurator;

public class ConfigureLog4J {
	
	private static String logFile = com.bearingnavi.android.BearingNaviActivity.appDir + "/log.txt";
	
	private Logger log = Logger.getLogger(getClass());
	
	public ConfigureLog4J() {
		Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
			
			public void uncaughtException(Thread thread, Throwable ex) {
				log.fatal(ex, ex);
			}
		});
	}
	
	public void uploadLog(String deviceId) {
		
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;

		String pathToOurFile = logFile;
		String urlServer = "http://bearingnavi.myartsonline.com/handle-upload.php";
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary =  "*****";

		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1*1024*1024;

		try
		{
			FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
	
			URL url = new URL(urlServer);
			connection = (HttpURLConnection) url.openConnection();
	
			// Allow Inputs & Outputs
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
	
			// Enable POST method
			connection.setRequestMethod("POST");
	
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
	
			outputStream = new DataOutputStream( connection.getOutputStream() );
			outputStream.writeBytes(twoHyphens + boundary + lineEnd);
			String datetime = DateFormat.format("yyyyMMddhhmmss", new Date()).toString();
			outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
					+ pathToOurFile.replace(".txt", "-"+deviceId+"-"+datetime+".txt") +"\"" + lineEnd);
			outputStream.writeBytes(lineEnd);
	
			bytesAvailable = fileInputStream.available();
			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];
	
			// Read file
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	
			while (bytesRead > 0)
			{
				outputStream.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}
			
			outputStream.writeBytes(lineEnd);
			outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
			
			// Responses from the server (code and message)
			int responseCode = connection.getResponseCode();
			log.debug("upload response code: "+responseCode);
			
			fileInputStream.close();
			outputStream.flush();
			outputStream.close();
			
			if (responseCode == 200) {
				
				log.debug("upload success");
				
				FileWriter writer = new FileWriter(pathToOurFile, false);
				writer.write("");
				writer.flush();
				writer.close();
			}
		}
		catch (IOException ex)
		{
			log.error(ex, ex);
		}
	}
	
	static {
		final LogConfigurator logConfigurator = new LogConfigurator();

		logConfigurator.setFileName(logFile);
		logConfigurator.setRootLevel(Level.DEBUG);
		// Set log level of a specific logger
		logConfigurator.setLevel("org.apache", Level.ERROR);
		logConfigurator.setFilePattern("%-5p: %d{ISO8601} %t: %C{1}: %m%n");
		logConfigurator.configure();

	}
}
